package v1

import (
	"github.com/gin-gonic/gin"
	"mall_2.0/pkg/utils/ctl"
	"mall_2.0/pkg/utils/log"
	"mall_2.0/service"
	"mall_2.0/types"
	"net/http"
)

// CreateCartHandler 创建购物车
func CreateCartHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.CartCreateReq
		if err := c.ShouldBind(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetCartSrv()
		resp, err := l.CartCreate(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}

// ListCartHandler 获取购物车列表
func ListCartHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.CartListReq
		if err := c.ShouldBind(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetCartSrv()
		resp, err := l.CartList(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}

// UpdateCartHandler 更新购物车
func UpdateCartHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.UpdateCartServiceReq
		if err := c.ShouldBind(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetCartSrv()
		resp, err := l.CartUpdate(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}

// DeleteCartHandler 删除购物车
func DeleteCartHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req types.CartDeleteReq
		if err := c.ShouldBind(&req); err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusBadRequest, ErrorResponse(c, err))
			return
		}
		l := service.GetCartSrv()
		resp, err := l.CartDelete(c.Request.Context(), &req)
		if err != nil {
			log.LogrusObj.Infoln(err)
			c.JSON(http.StatusInternalServerError, ErrorResponse(c, err))
			return
		}
		c.JSON(http.StatusOK, ctl.RespSuccess(c, resp))
	}
}
